package it.tukano.treditor.modules;

import it.tukano.app.AppModule;
import it.tukano.collections.MapExt;
import it.tukano.swingdeco.containers.JPanelExt;
import it.tukano.swingdeco.containers.JToolBarExt;
import it.tukano.swingdeco.controls.JToggleButtonExt;
import it.tukano.treditor.resources.Labels.LabelKey;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.Icon;

public class ToolbarModule extends BasicModule {
    
    private final MapExt<Object, ButtonGroup> buttonGroups = MapExt.newHashMap();
    private final JToolBarExt bar = new JToolBarExt().floatable(false);
    private final JPanelExt panel = new JPanelExt(new BorderLayout())
            .withName(getLabel(LabelKey.TOOLBAR))
            .append(bar);

    /**
     * Instance initializer
     */
    public ToolbarModule() {
    }

    @Override
    public void startModule(AppModule context) {
        super.startModule(context);
        invokeWithModules("installUi", MainFrame.class);
    }
    
    public void installUi(MainFrame mainFrame) {
        mainFrame.install(panel, BorderLayout.NORTH, false);
    }
    
    public void createToggleButton(Object groupIndex, Icon icon, Runnable whenActivated, Runnable whenDeactivated) {
        Dimension preSize = bar.getPreferredSize();
        JToggleButtonExt button = new JToggleButtonExt(icon)
                .onSelected(whenActivated)
                .onDeselected(whenActivated);
        buttonGroups.getOrAdd(groupIndex, new ButtonGroup()).add(button);
        bar.add(button);
        Dimension postSize = bar.getPreferredSize();
        if(!preSize.equals(postSize)) invokeWithModules("repackRegion", MainFrame.class);
    }
    
    public void registerButtonToGroup(AbstractButton button, Object groupIndex) {
        buttonGroups.getOrAdd(groupIndex, new ButtonGroup()).add(button);
    }
    
    public void repackRegion(MainFrame frame) {
        frame.repackTab(panel);
    }
}
